local PT = LibStub("LibPeriodicTable-3.1")

--SimpleTradeskill = AceLibrary("AceAddon-2.0"):new("AceEvent-2.0", "AceHook-2.1")
local addon = CreateFrame("Frame")
local _G = _G

local hooks = {}
function addon:SecureHook(original, hook)
	if not hook then hook = original end
	if not hooks[original] then hooks[original] = {} end
	if hooks[original][hook] then return end
	hooks[original][hook] = true
	hooksecurefunc(original, function(...) self[hook](self, ...) end)
end

addon:SetScript("OnEvent", function(self, event, ...)
	if self[event] then self[event](self, event, ...) end
end)
addon:RegisterEvent("ADDON_LOADED")

function addon:ADDON_LOADED(event, addon_name)
	--if addon_name ~= "SimpleTradeskill" then return end
	self:UnregisterEvent("ADDON_LOADED")
	self:RegisterEvent("TRADE_SKILL_SHOW")
end

local function SplitLink(link)
	-- link is "|cffffffff|Hitem:13928:0:0:0:0:0:0:0|h[Grilled Squid]|h|r" or "|cffffffff|Henchant:7421|h[Runed Copper Rod]|h|r"
	return link:match("^.*|H(%l+):(%d+).*|h%[(.*)%]|h|r$")
end

local function GetHowManyCanBeMade(index)
	local buy, bank = 10000, 10000 -- 10000 is just an arbitrarily high number
	local sname,_,base = GetTradeSkillInfo(index)
	if base == -1 then
		return -1
	end
	local numReagents = GetTradeSkillNumReagents(index)
	for id=1, numReagents, 1 do
		local link = GetTradeSkillReagentItemLink(index, id)
		if not link then return base,0,0 end -- item isn't cached
		--Skip vendor-buyable items
		if not PT:ItemInSet(link, "Tradeskill.Mat.BySource.Vendor") then
			local name, texture, required, have = GetTradeSkillReagentInfo(index, id)
			local cap = math.floor(have / required)
			local bankcap = math.floor(GetItemCount(link, true) / required)
			if cap < buy then buy = cap end
			if bankcap < bank then bank = bankcap end
		end
	end
	if buy == 10000 then buy = 0 end
	if bank == 10000 then bank = 0 end
	return base, buy, bank
end
addon.GetHowManyCanBeMade = GetHowManyCanBeMade

-- Prettify the tradeskill window
function addon:TRADE_SKILL_SHOW()
	self:SecureHook("TradeSkillFrame_Update", "TRADE_SKILL_SHOW")
	self:SecureHook("TradeSkillFrame_SetSelection")
	if TradeSkillFrame:IsVisible() then
		self:UpdateWindow(FauxScrollFrame_GetOffset(TradeSkillListScrollFrame), TRADE_SKILLS_DISPLAYED)
	end
end

function addon:UpdateWindow(skillOffset, displayed)
	local numSkills = GetNumTradeSkills()
	if numSkills > 0 then
		for i=1, displayed, 1 do
			local skillIndex = i + skillOffset
			local skillName, skillType, numAvailable, isExpanded = GetTradeSkillInfo(skillIndex)
			local skillButtonCount = _G["TradeSkillSkill"..i.."Count"];
			if skillName and (skillIndex <= numSkills) then
				if skillType ~= 'header' then
					local base, buy, bank = GetHowManyCanBeMade(skillIndex)
					if not ((base == -1) or ((base == 0) and (buy == 0) and (bank == 0))) then
						skillButtonCount:SetText('[' .. base .. (buy > base and ('/V' .. buy) or '') .. (bank > buy and ('/B' .. bank) or '') .. ']')

						-- and size appropriately:
						local skillButtonText = _G["TradeSkillSkill"..i.."Text"];
						TradeSkillFrameDummyString:SetText(skillName);
						local nameWidth = TradeSkillFrameDummyString:GetWidth();
						local countWidth = skillButtonCount:GetWidth();
						if nameWidth + 2 + countWidth > TRADE_SKILL_TEXT_WIDTH then
							skillButtonText:SetWidth(TRADE_SKILL_TEXT_WIDTH - 2 - countWidth);
						else
							skillButtonText:SetWidth(0);
						end
					end
				end
			end
		end
	end
end

function addon:TradeSkillFrame_SetSelection(id)
	local numReagents = GetTradeSkillNumReagents(id)
	for i=1, numReagents, 1 do
		local link = GetTradeSkillReagentItemLink(id, i)
		if link and PT:ItemInSet(link, "Tradeskill.Mat.BySource.Vendor") then
			local button = _G["TradeSkillReagent"..i..'Name']
			local text = button:GetText()
			if text then
				button:SetText(button:GetText() .. '*')
			end
		end
	end
end
